package org.example.project.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.example.bean.Logistics;
import org.example.config.JwtConfig;
import org.example.mapper.LogisticsMapper;
import org.example.project.bookstore.service.LogisticsService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:LogisticsServiceImpl
 * @Date:2025/8/25 16:21
 */
@Service
public class LogisticsServiceImpl extends ServiceImpl<LogisticsMapper, Logistics> implements LogisticsService {

    /**
     * 查找地址
     *
     * @param token
     * @return
     */
    @Override
    public JsonResult findUserId(String token) {
        Claims claims = JwtConfig.parseJWT(token);
        String userId = claims.get("id").toString();
        QueryWrapper<Logistics> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.orderByAsc("status");
        List<Logistics> list = list(wrapper);
        return ResultTool.success(list);
    }

    /**
     * 添加地址
     *
     * @param logistics
     * @param token
     * @return
     */
    @Override
    public JsonResult saveLogistics(Logistics logistics, String token) {
        Claims claims = JwtConfig.parseJWT(token);
        String userId = claims.get("id").toString();
        logistics.setUserId(userId);
        QueryWrapper<Logistics> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        long count = count(wrapper);
        // 第一次添加
        if (count == 0) {
            logistics.setStatus(1);
            save(logistics);
            return ResultTool.success("success");
        }
        //不是第一次
        //是非常用地址
        Integer status = logistics.getStatus();
        if (status == 2) {
            save(logistics);
            return ResultTool.success("success");
        }
        //是常用地址
        logistics.setStatus(1);
        UpdateWrapper<Logistics> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId);
        updateWrapper.set("status", 2);
        updateWrapper.eq("status", 1);
        update(updateWrapper);
        save(logistics);
        return ResultTool.success("success");
    }
}
